package com.jeesuite.bestpl.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jeesuite.bestpl.dao.entity.UserEntity;
import com.jeesuite.bestpl.dao.mapper.UserEntityMapper;
import com.jeesuite.bestpl.dto.Page;
import com.jeesuite.bestpl.dto.PageMetaInfo;
import com.jeesuite.bestpl.dto.PageQueryParam;
import com.jeesuite.bestpl.dto.Post;
import com.jeesuite.bestpl.dto.WrapperResponseEntity;
import com.jeesuite.bestpl.exception.JeesuiteBaseException;
import com.jeesuite.bestpl.security.PasswordUtils;
import com.jeesuite.bestpl.security.SecurityUtil;
import com.jeesuite.bestpl.service.PostApiService;
import com.jeesuite.bestpl.service.UserService;

@Controller
@RequestMapping("/ucenter")
public class UCenterController {
	
	private static final String PNG = "png";
	
	private final static int DEFAULT_PAGE_SIZE = 10;
	private static List<String> allow_upload_suffix = new ArrayList<>(Arrays.asList("png","jpg","jpeg"));
	
	@Value("${upload.base.path}")
	private String uploadBasepath;

	@Autowired
	private UserEntityMapper userMapper;
	private @Autowired PostApiService postService;
	private @Autowired UserService userService;
	
	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(Model model){
		model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("ucenter"));
		
		return "ucenter/index";
	}
	
	@RequestMapping(value = "setting", method = RequestMethod.GET)
	public String setting(Model model){
		model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("ucenter"));
		
		return "ucenter/setting";
	}
	
	@RequestMapping(value = "message", method = RequestMethod.GET)
	public String message(Model model){
		model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("ucenter"));
		
		return "ucenter/message";
	}
	
	@RequestMapping(value = "my/{type}", method = RequestMethod.POST)
	public @ResponseBody Page<Post> myPosts(@PathVariable(value="type") String sortType,@RequestParam(value="page",required=false) int pageNo){
		PageQueryParam param = new PageQueryParam(pageNo <= 0 ? 1 : pageNo,DEFAULT_PAGE_SIZE);
		param.getConditions().put("userId", SecurityUtil.getLoginUserId());
		return postService.pageQueryPost(param);
	}
	
	@RequestMapping(value = "updatepwd", method = RequestMethod.POST)
	public ResponseEntity<WrapperResponseEntity<Object>> bindSnsAccount(HttpServletRequest request,@RequestBody Map<String, String> params){

		String oldPassword = StringUtils.trimToEmpty(params.get("oldPassword"));
		UserEntity userEntity = userMapper.selectByPrimaryKey(SecurityUtil.getLoginUserId());
		if(!userEntity.getPassword().equals(PasswordUtils.encrypt(oldPassword, userEntity.getUsername()))){
			return new ResponseEntity<WrapperResponseEntity<Object>>(new WrapperResponseEntity<Object>(4001, "原密码错误"),HttpStatus.OK);
		}
		userEntity.setPassword(StringUtils.trimToEmpty(params.get("password")));
		userService.updateUser(userEntity);
		
		return new ResponseEntity<WrapperResponseEntity<Object>>(new WrapperResponseEntity<Object>(true),HttpStatus.OK);
	}
	
	@RequestMapping(value = "upload_avatar", method = RequestMethod.POST)
	public ResponseEntity<Object> uploadConfigFile(@RequestParam("file") MultipartFile file){
		BufferedOutputStream stream = null;
		FileOutputStream outputStream = null;
		try {
			
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
			if(!allow_upload_suffix.contains(suffix.toLowerCase())){
				throw new JeesuiteBaseException(9999, "不允许上传该文件类型");
			}
			
			Map<String, String> result = new HashMap<>();
			int loginUserId = SecurityUtil.getLoginUserId();
			String savepath = buildAvatarPath(loginUserId);
			
			if(PNG.equalsIgnoreCase(suffix)){				
				outputStream = new FileOutputStream(new File(uploadBasepath + savepath));
				stream = new BufferedOutputStream(outputStream);  
				stream.write(file.getBytes());  
				stream.flush();
			}else{				
				BufferedImage bim = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
				File output = new File(uploadBasepath + savepath);
				ImageIO.write(bim, PNG, output);
			}
            
            UserEntity userEntity = new UserEntity();
            userEntity.setId(loginUserId);
            userEntity.setAvatar(savepath);
            
            userService.updateUser(userEntity);
            
			return new ResponseEntity<Object>(new WrapperResponseEntity<Object>(result),HttpStatus.OK);
		} catch (Exception e) {
			e.printStackTrace();
			throw new JeesuiteBaseException(9999, "修改失败");
		}finally {
			try {if(outputStream != null)outputStream.close(); } catch (Exception e2) {}
			try {if(stream != null)stream.close(); } catch (Exception e2) {}
		}
	}
	
	private String buildAvatarPath(int userId){
		String leve1Dir = String.valueOf(userId % 100);
		return String.format("/%s/%s/%s.png", "avatar",leve1Dir,userId);
	}
	

}
